package org.pro.browser.config;

import org.pro.core.validateCode.ValidateCode;
import org.pro.core.validateCode.ValidateCodeType;
import org.pro.core.validateCode.repository.ValidateCodeRepository;

import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;

import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;

/**
 * 浏览器端将验证码放入session中
 * @author luoqiz
 *
 */
@Component
public class SessionValidateCodeRepository implements ValidateCodeRepository {

	/**
	 * 验证码放入session的前缀
	 */
	String SESSION_KEY_PREFIX="SESSION_KEY_FOR_CODE_";
	/**
	 * 操作session的工具类
	 */
	private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
	
	@Override
	public void save(ServletWebRequest request, ValidateCode code, ValidateCodeType validateCodeType) {
		sessionStrategy.setAttribute(request,getSessionKey(request,validateCodeType) , code);
//		request.setAttribute(getSessionKey(request,validateCodeType), validateCodeType, 1);
	}

	@Override
	public ValidateCode get(ServletWebRequest request, ValidateCodeType validateCodeType) {
		return (ValidateCode) sessionStrategy.getAttribute(request, getSessionKey(request,validateCodeType));
	}

	@Override
	public void remove(ServletWebRequest request, ValidateCodeType validateCodeType) {
		sessionStrategy.removeAttribute(request, getSessionKey(request,validateCodeType));		
	}

	/**
	 * 构建验证码放入session时的key
	 * 
	 * @param request
	 * @param validateCodeType 
	 * @return
	 */
	private String getSessionKey(ServletWebRequest request, ValidateCodeType validateCodeType) {
		return SESSION_KEY_PREFIX + validateCodeType.toString().toUpperCase();
	}
}
